package com.ruoyi.base.service.impl;

import java.util.List;

import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ValidationUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.base.mapper.BaseClassMapper;
import com.ruoyi.base.mapper.BaseSpecialtyMapper;
import com.ruoyi.base.domain.BaseClass;
import com.ruoyi.base.domain.BaseSpecialty;
import com.ruoyi.base.service.IBaseClassService;

/**
 * 班级Service业务层处理
 * 
 * @author yepanpan
 * @date 2020-11-09
 */
@Service
public class BaseClassServiceImpl implements IBaseClassService 
{
	private static final Logger log = LoggerFactory.getLogger(BaseClassServiceImpl.class);
	
    @Autowired
    private BaseClassMapper baseClassMapper;
    @Autowired
    private BaseSpecialtyMapper baseSpecialtyMapper;

    /**
     * 查询班级
     * 
     * @param id 班级ID
     * @return 班级
     */
    @Override
    public BaseClass selectBaseClassById(Long id)
    {
        return baseClassMapper.selectBaseClassById(id);
    }

    /**
     * 查询班级列表
     * 
     * @param baseClass 班级
     * @return 班级
     */
    @Override
    public List<BaseClass> selectBaseClassList(BaseClass baseClass)
    {
        return baseClassMapper.selectBaseClassList(baseClass);
    }

    /**
     * 新增班级
     * 
     * @param baseClass 班级
     * @return 结果
     */
    @Override
    public int insertBaseClass(BaseClass baseClass)
    {
    	//判断固定教室是否可用
    	BaseClass bcc = new BaseClass();
    	bcc.setRoomId(baseClass.getRoomId());
    	List<BaseClass> list = baseClassMapper.selectBaseClassList(bcc);
    	if(list != null && list.size() > 0) {
    		for(BaseClass bc:list) {
    			if("0".equals(bc.getStatus())) {
    				bc.setRoomId(0l);
    				baseClassMapper.updateBaseClass(bc);
    			}else {
    				throw new CustomException("固定教室已经被 "+bc.getTitle()+" 占用");
    			}
    		}
    	}
    	
        baseClass.setCreateTime(DateUtils.getNowDate());
        return baseClassMapper.insertBaseClass(baseClass);
    }

    /**
     * 修改班级
     * 
     * @param baseClass 班级
     * @return 结果
     */
    @Override
    public int updateBaseClass(BaseClass baseClass)
    {
    	//判断固定教室是否可用
    	BaseClass bcc = new BaseClass();
    	bcc.setRoomId(baseClass.getRoomId());
    	List<BaseClass> list = baseClassMapper.selectBaseClassList(bcc);
    	if(list != null && list.size() > 0) {
    		for(BaseClass bc:list) {
    			if(bc.getId().equals(baseClass.getId())) continue;
    			
    			if("0".equals(bc.getStatus())) {
    				bc.setRoomId(0l);
    				baseClassMapper.updateBaseClass(bc);
    			}else {
    				throw new CustomException("固定教室已经被 "+bc.getTitle()+" 占用");
    			}
    		}
    	}
    	
        baseClass.setUpdateTime(DateUtils.getNowDate());
        return baseClassMapper.updateBaseClass(baseClass);
    }

    /**
     * 批量删除班级
     * 
     * @param ids 需要删除的班级ID
     * @return 结果
     */
    @Override
    public int deleteBaseClassByIds(Long[] ids)
    {
        return baseClassMapper.deleteBaseClassByIds(ids);
    }

    /**
     * 删除班级信息
     * 
     * @param id 班级ID
     * @return 结果
     */
    @Override
    public int deleteBaseClassById(Long id)
    {
        return baseClassMapper.deleteBaseClassById(id);
    }
    
    
    /**
     * 修改班级状态
     * 
     * @param ids 需要修改的班级ID
     * @param status 新的状态
     * @return 结果
     */
    @Override
    public int updateBaseClassStatus(Long[] ids, String status) {
    	return baseClassMapper.updateBaseClassStatus(ids, status);
    }
    

    /**
     * 设置班级为毕业状态
     * 
     * @param ids 需要设置为毕业状态的班级ID
     * @return 结果
     */
    @Override
    @Transactional
    public int graduationClass(Long[] ids) {
    	int count = 0;
    	for(Long id:ids) {
    		BaseClass bc = baseClassMapper.selectBaseClassById(id);
    		bc.setStatus("0");
    		bc.setEndDate(DateUtils.getNowDate());
    		bc.setRoomId(0l);
    		count += baseClassMapper.updateBaseClass(bc);
    	}
    	return count;
    }
    
    /**
     * 导入班级数据
     * 
     * @param clazzList 班级数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importClass(List<BaseClass> clazzList, Boolean isUpdateSupport, String operName) {
    	if (StringUtils.isNull(clazzList) || clazzList.size() == 0)
        {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseClass vo : clazzList)
        {
        	List<String> vs = ValidationUtils.validate(vo);
        	if(vs != null) {
        		failureNum++;
                failureMsg.append("<br/>" + failureNum + "、班级 " + vo.getTitle() + " 数据不完整："+ CollectionUtils.join(vs, ","));
                continue;
        	}
            try
            {
                // 验证部门是否存在
            	BaseSpecialty dd = baseSpecialtyMapper.findSpecialtyByName(vo.getSpecName());
            	if(dd == null) {
            		throw new CustomException("专业不"+vo.getSpecName()+"存在");
            	}
            	vo.setSpecId(dd.getId());
            	
            	//查找旧数据
            	BaseClass old = baseClassMapper.findClassByCode(vo.getCode());
                if (StringUtils.isNull(old))
                {
                    this.insertBaseClass(vo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、班级 " + vo.getTitle() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    vo.setId(old.getId());
                    this.updateBaseClass(vo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、班级 " + vo.getTitle() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、班级 " + vo.getTitle() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、班级 " + vo.getTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
